package com.zjy.business.system.dao;

import com.zjy.business.system.domain.entity.SysMenu;
import com.zjy.business.system.domain.manager.vo.ManagerSysMenuListVo;
import com.zjy.business.system.mapper.SysMenuMapper;
import com.zjy.common.constant.StatusEnums;
import com.zjy.common.utils.StreamUtils;
import com.zjy.config.RedisServiceImpl;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author yxb
 * create_time: 2024-10-22 14:44
 * description: 
 */
@Service
public class SysMenuDao extends RedisServiceImpl<SysMenuMapper, SysMenu> {

    @Resource
    @Lazy
    private SysRoleMenuDao sysRoleMenuDao;

    /**
     * 根据用户id获取权限
     * @param userId 用户id
     * @return
     */
    public List<String> getPermissionByUserId(Long userId) {
        List<Long> menuIds = sysRoleMenuDao.queryMenuIdByUserId(userId);
        return StreamUtils.toList(findCacheOneByMoreParam(SysMenu::getId, menuIds).values(), item -> {
            if (Objects.equals(item.getStatus(), StatusEnums.PUBLIC_STATUS_NORMAL.getStatus()) && StringUtils.isNotBlank(item.getPerms())) {
                return item.getPerms();
            }
            return null;
        });
    }

    /**
     * 根据父菜单ID和菜单数据获取菜单列表
     *
     * @param parentId 父菜单的ID，用于查找子菜单
     * @param dataMap  包含所有菜单数据的映射，键为菜单ID，值为子菜单列表
     * @return 返回指定父菜单下的菜单列表，如果无子菜单则返回空列表
     */
    public List<ManagerSysMenuListVo> getSysMenuList(Long parentId, Map<Long, List<ManagerSysMenuListVo>> dataMap) {
        List<ManagerSysMenuListVo> result = dataMap.get(parentId);
        if (ObjectUtils.isNotEmpty(result)) {
            for (ManagerSysMenuListVo item : result) {
                item.setChildren(getSysMenuList(item.getId(), dataMap));
            }
            return result.stream().sorted(Comparator.comparing(ManagerSysMenuListVo::getOrderNum)).toList();
        }
        return result;
    }

}
